package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"manuscript-service/models/mysql"
	"manuscript-service/models/redis"
	"time"

	"manuscript-service/manuscriptrpc/internal/svc"
	"manuscript-service/manuscriptrpc/manuscriptrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptFindLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptFindLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptFindLogic {
	return &ManuscriptFindLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 稿件列表接口
func (l *ManuscriptFindLogic) ManuscriptFind(in *manuscriptrpc.ManuscriptFindRequest) (*manuscriptrpc.ManuscriptFindResponse, error) {
	// todo: add your logic here and delete this line

	var list []*manuscriptrpc.ManuscriptFind

	var err error

	key := fmt.Sprintf("manuscript_list")

	result, _ := redis.Rdb.Get(l.ctx, key).Result()

	if result == "" {
		list, err = mysql.ManuscriptList(mysql.DB)
		if err != nil {
			return nil, err
		}
		marshal, _ := json.Marshal(list)
		redis.Rdb.Set(l.ctx, key, marshal, time.Minute*120)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &manuscriptrpc.ManuscriptFindResponse{
		List: list,
	}, nil
}
